package server

import (
	"fmt"
	"net/http"

	"github.com/labstack/echo"
	"go.uber.org/zap"
)

// Echo ...
type Echo struct {
}

// NewEcho ....
func NewEcho() *Echo {
	return &Echo{}
}

// Start ...
func (e *Echo) Start() {
	echo := echo.New()

	echo.POST("/", keeplive)
	echo.GET("/getlink", getLink)
	echo.POST("/getlink", getLink)
	err := echo.Start(Conf.EchoC.Addr)
	if err != nil {
		Logger.Fatal("echo start", zap.Error(err))
	}
}

// keeplive
func keeplive(c echo.Context) error {
	name := c.FormValue("name")
	if name == "" {
		Logger.Info("keeplive", zap.Error(fmt.Errorf("unfind name")))
		return nil
	}

	host := c.FormValue("host")
	Logger.Info("keeplive", zap.String("name", name), zap.String("host", host))

	if _, ok := gServer.agents.Get(name); !ok {
		agent := NewAgent()
		gServer.agents.Insert(name, agent)
		// 创建监控表单
		gServer.grafana.CreateDashboard(name)
	}

	c.JSON(http.StatusOK, "ok")
	return nil
}

// getLink
func getLink(c echo.Context) error {
	name := c.FormValue("name")
	if name == "" {
		Logger.Warn("keeplive", zap.Error(fmt.Errorf("unfind name")))
		return nil
	}
	query := fmt.Sprintf("SELECT `url` from `app` WHERE `name` = '%s';", name)
	rows, err := gServer.sql.DB.Query(query)
	if err != nil {
		return err
	}
	defer rows.Close()

	var url string
	find := false
	for rows.Next() {
		err := rows.Scan(&url)
		if err != nil {
			Logger.Warn("Scan", zap.Error(err))
			continue
		}
		find = true
		break
	}
	if !find {
		Logger.Warn("getLink", zap.Error(fmt.Errorf("unfind name")), zap.String("name", name))
		return fmt.Errorf("unfind name %s ", name)
	}
	url = gServer.grafana.addr + url
	c.JSON(http.StatusOK, url)
	return nil
}
